﻿using System.Web.Mvc;
using DotNetBurner.Web.Settings;

namespace DotNetBurner.Web
{
    public class ReCaptchaValidatorFilterAttribute : ActionFilterAttribute
    {
        private const string ChallengeFieldKey = "recaptcha_challenge_field";
        private const string ResponseFieldKey = "recaptcha_response_field";

        public override void OnActionExecuting(ActionExecutingContext filterContext)  
        {  
            var captchaChallengeValue = filterContext.HttpContext.Request.Form[ChallengeFieldKey];  
            var captchaResponseValue = filterContext.HttpContext.Request.Form[ResponseFieldKey];  
            var captchaValidtor = new Recaptcha.RecaptchaValidator  
                                      {  
                                          PrivateKey = CaptchaSettings.Settings.PrivateKey,
                                          RemoteIP = filterContext.HttpContext.Request.UserHostAddress,  
                                          Challenge = captchaChallengeValue,  
                                          Response = captchaResponseValue  
                                      };  
  
            var recaptchaResponse = captchaValidtor.Validate();  
  
            // this will push the result value into a parameter in our Action  
            filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;  
  
            base.OnActionExecuting(filterContext);  
        }
    }  
}
